'use client'

import { useState, useEffect } from 'react'
import { 
  setTabToken, 
  getTabToken, 
  clearTabToken, 
  hasValidTabToken,
  getAllTabTokens,
  getAllActiveTokens,
  clearAllTabTokens,
  getCacheInfo
} from '@/lib/cache'

export default function CacheTestPage() {
  const [token, setToken] = useState<string>('')
  const [currentToken, setCurrentToken] = useState<string | null>(null)
  const [hasToken, setHasToken] = useState<boolean>(false)
  const [allTokens, setAllTokens] = useState<any[]>([])
  const [activeTokens, setActiveTokens] = useState<any[]>([])
  const [cacheInfo, setCacheInfo] = useState<any>(null)
  const [logs, setLogs] = useState<string[]>([])

  // 添加日志
  const addLog = (message: string) => {
    const timestamp = new Date().toLocaleTimeString()
    setLogs(prev => [`[${timestamp}] ${message}`, ...prev.slice(0, 19)])
  }

  // 刷新状态
  const refreshStatus = () => {
    const token = getTabToken()
    const hasValid = hasValidTabToken()
    const all = getAllTabTokens()
    const active = getAllActiveTokens()
    const info = getCacheInfo()

    setCurrentToken(token)
    setHasToken(hasValid)
    setAllTokens(all)
    setActiveTokens(active)
    setCacheInfo(info)

    addLog(`状态刷新完成 - 当前token: ${token ? '有' : '无'}`)
  }

  // 设置token
  const handleSetToken = () => {
    if (!token.trim()) {
      addLog('❌ 请输入token')
      return
    }

    setTabToken(token.trim())
    addLog(`✅ Token已设置: ${token.substring(0, 20)}...`)
    refreshStatus()
  }

  // 清除token
  const handleClearToken = () => {
    clearTabToken()
    addLog('🧹 Token已清除')
    refreshStatus()
  }

  // 清除所有token
  const handleClearAllTokens = () => {
    clearAllTabTokens()
    addLog('🧹 所有Token已清除')
    refreshStatus()
  }

  // 页面刷新测试
  const handleRefreshTest = () => {
    addLog('🔄 即将刷新页面测试token恢复...')
    setTimeout(() => {
      window.location.reload()
    }, 1000)
  }

  useEffect(() => {
    refreshStatus()
    addLog('📱 页面加载完成')
  }, [])

  return (
    <div className="p-6 max-w-6xl mx-auto">
      <h1 className="text-2xl font-bold mb-6">缓存管理测试页面</h1>
      
      {/* Token操作区域 */}
      <div className="bg-white rounded-lg shadow-md p-6 mb-6">
        <h2 className="text-xl font-semibold mb-4">Token操作</h2>
        
        <div className="flex gap-4 mb-4">
          <input
            type="text"
            value={token}
            onChange={(e) => setToken(e.target.value)}
            placeholder="输入token"
            className="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          />
          <button
            onClick={handleSetToken}
            className="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500"
          >
            设置Token
          </button>
          <button
            onClick={handleClearToken}
            className="px-4 py-2 bg-red-500 text-white rounded-md hover:bg-red-600 focus:outline-none focus:ring-2 focus:ring-red-500"
          >
            清除Token
          </button>
        </div>

        <div className="flex gap-4">
          <button
            onClick={handleClearAllTokens}
            className="px-4 py-2 bg-orange-500 text-white rounded-md hover:bg-orange-600 focus:outline-none focus:ring-2 focus:ring-orange-500"
          >
            清除所有Token
          </button>
          <button
            onClick={handleRefreshTest}
            className="px-4 py-2 bg-green-500 text-white rounded-md hover:bg-green-600 focus:outline-none focus:ring-2 focus:ring-green-500"
          >
            测试页面刷新
          </button>
          <button
            onClick={refreshStatus}
            className="px-4 py-2 bg-gray-500 text-white rounded-md hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-gray-500"
          >
            刷新状态
          </button>
        </div>
      </div>

      {/* 状态显示区域 */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
        {/* 当前状态 */}
        <div className="bg-white rounded-lg shadow-md p-6">
          <h3 className="text-lg font-semibold mb-4">当前状态</h3>
          <div className="space-y-2">
            <div className="flex justify-between">
              <span className="font-medium">当前Token:</span>
              <span className={currentToken ? 'text-green-600' : 'text-red-600'}>
                {currentToken ? '有' : '无'}
              </span>
            </div>
            <div className="flex justify-between">
              <span className="font-medium">有效Token:</span>
              <span className={hasToken ? 'text-green-600' : 'text-red-600'}>
                {hasToken ? '是' : '否'}
              </span>
            </div>
            <div className="flex justify-between">
              <span className="font-medium">Token值:</span>
              <span className="text-sm text-gray-600 font-mono">
                {currentToken ? `${currentToken.substring(0, 30)}...` : '无'}
              </span>
            </div>
          </div>
        </div>

        {/* 缓存信息 */}
        <div className="bg-white rounded-lg shadow-md p-6">
          <h3 className="text-lg font-semibold mb-4">缓存信息</h3>
          {cacheInfo && (
            <div className="space-y-2">
              <div className="flex justify-between">
                <span className="font-medium">localStorage:</span>
                <span className="text-sm text-gray-600">
                  {(cacheInfo.localStorage / 1024).toFixed(2)} KB
                </span>
              </div>
              <div className="flex justify-between">
                <span className="font-medium">sessionStorage:</span>
                <span className="text-sm text-gray-600">
                  {(cacheInfo.sessionStorage / 1024).toFixed(2)} KB
                </span>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* 标签页Token列表 */}
      <div className="bg-white rounded-lg shadow-md p-6 mb-6">
        <h3 className="text-lg font-semibold mb-4">所有标签页Token</h3>
        <div className="overflow-x-auto">
          <table className="min-w-full">
            <thead>
              <tr className="border-b">
                <th className="text-left py-2">标签页ID</th>
                <th className="text-left py-2">Token</th>
                <th className="text-left py-2">是否当前</th>
                <th className="text-left py-2">最后活动</th>
              </tr>
            </thead>
            <tbody>
              {allTokens.map((tab, index) => (
                <tr key={index} className="border-b hover:bg-gray-50">
                  <td className="py-2 text-sm font-mono">{tab.tabId}</td>
                  <td className="py-2 text-sm">
                    {tab.token ? `${tab.token.substring(0, 20)}...` : '无'}
                  </td>
                  <td className="py-2">
                    <span className={tab.isCurrent ? 'text-green-600' : 'text-gray-500'}>
                      {tab.isCurrent ? '是' : '否'}
                    </span>
                  </td>
                  <td className="py-2 text-sm text-gray-600">
                    {tab.lastActivity ? new Date(tab.lastActivity).toLocaleString() : '未知'}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* 活跃Token列表 */}
      <div className="bg-white rounded-lg shadow-md p-6 mb-6">
        <h3 className="text-lg font-semibold mb-4">活跃Token</h3>
        <div className="overflow-x-auto">
          <table className="min-w-full">
            <thead>
              <tr className="border-b">
                <th className="text-left py-2">标签页ID</th>
                <th className="text-left py-2">Token</th>
                <th className="text-left py-2">最后活动</th>
              </tr>
            </thead>
            <tbody>
              {activeTokens.map((tab, index) => (
                <tr key={index} className="border-b hover:bg-gray-50">
                  <td className="py-2 text-sm font-mono">{tab.tabId}</td>
                  <td className="py-2 text-sm">{tab.token}</td>
                  <td className="py-2 text-sm text-gray-600">
                    {new Date(tab.lastActivity).toLocaleString()}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* 操作日志 */}
      <div className="bg-white rounded-lg shadow-md p-6">
        <h3 className="text-lg font-semibold mb-4">操作日志</h3>
        <div className="bg-gray-100 p-4 rounded-md h-64 overflow-y-auto">
          {logs.length === 0 ? (
            <p className="text-gray-500">暂无日志</p>
          ) : (
            logs.map((log, index) => (
              <div key={index} className="text-sm font-mono mb-1">
                {log}
              </div>
            ))
          )}
        </div>
      </div>
    </div>
  )
}
